import { useState, useEffect } from "react";
import { getCategory } from "@/utils/back/index";
import { searchArticle } from "@/utils/front/index";

const useCategory = () => {
  const [categoryData, setCategoryData] = useState({
    length: 0,
    categoriesWithArticles: [],
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchData = async () => {
    try {
      const res: any = await getCategory();
      if (res.status === 200) {
        const length = res.data.length;
        const categoriesWithArticles: any = await Promise.all(
          res.data.map(async (category: any) => {
            const articles = await Promise.all(
              category.articleIds.map(async (articleId: any) => {
                try {
                  const articleRes: any = await searchArticle(articleId);
                  if (articleRes.status === 200) {
                    return articleRes.data[0].title;
                  } else {
                    throw new Error("请求文章失败，文章 ID：" + articleId);
                  }
                } catch (error) {
                  console.error("请求文章出现错误:", error);
                  return "";
                }
              })
            );

            return {
              categoryName: category.categoryName,
              categoriesId: category.categoriesId,
              articles: articles.filter((article) => article !== ""),
            };
          })
        );
        setCategoryData({ length, categoriesWithArticles });
      } else {
        throw new Error("请求失败，状态码：" + res.status);
      }
    } catch (error: any) {
      console.error("请求出现错误:", error);
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  const refresh = () => {
    setLoading(true);
    fetchData();
  };

  useEffect(() => {
    fetchData();
  }, []);

  return { ...categoryData, loading, error, refresh };
};

export default useCategory;
